package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class InitParamServlet
 */
@WebServlet(
		urlPatterns = { "/InitParamServlet" }, 
		initParams = { 
				@WebInitParam(name = "admin", value = "admin"), 
				@WebInitParam(name = "root", value = "root")
		})
public class InitParamServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public InitParamServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");    //设置request编码
		response.setCharacterEncoding("utf-8");     //设置response编码
		
		response.setContentType("text/html");     //设置响应类型为html
		
		PrintWriter out = response.getWriter();
		
		//登陆界面
		out.println("<html>");
		out.println("<head><title>登陆</title></head>");
		out.println("<body>");
		out.println("<form action='"+request.getRequestURI()+"' method='post'>");
		out.println("<table>");
		out.println("<tr>");
		out.println("<td>用户名:</td>");
		out.println("<td><input type='text' name='username' /></td>");
		out.println("</tr>");
		out.println("<tr>");
		out.println("<td>密码:</td>");
		out.println("<td><input type='password' name='password' /></td>");
		out.println("</tr>");
		out.println("<tr>");
		out.println("<td colspan='2'><input type='submit' value='登陆' /></td>");
		out.println("</tr>");
		out.println("</table>");
		out.println("</form>");
		out.println("</body>");
		out.println("</html>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");   //获取登陆界面的用户名
		String password = request.getParameter("password");   //获取登陆界面的密码
		
		Enumeration para = this.getInitParameterNames();     //获取所有初始化参数的名称
		while(para.hasMoreElements()){
			String paraUsername = (String) para.nextElement();   //获取初始化参数名称
			String paraPassword = this.getInitParameter(paraUsername);   //获取初始化参数名称对应的密码
			if(paraUsername.equals(username)&&paraPassword.equals(password)){
				request.getRequestDispatcher("/WEB-INF/notice.html").forward(request, response);//如果用户名密码匹配则显示/WEB-INF下的notice.html
			}
		}
		this.doGet(request, response);  //若不匹配则显示登陆界面
	}

}
